<?php
namespace Home\Controller;

use Think\Controller;

class WechatController extends Controller
{
    const ROOM_ORDER_SUCCESS = '8JvvRHdxShataKHhLGMbbhLau1BlIskPlJtHq4ucrW0';
    const GOODS_ORDER_SUCCESS = '8JvvRHdxShataKHhLGMbbhLau1BlIskPlJtHq4ucrW0';
    const WXPAY_REFUND_SUCCESS = 'p-27U9sqqJA-fbC7PoeSNUDjbza8XW6p9tiK2OWW4KE';
    const SAVE_REFUND_fAILED = 'gFWJauxcqJ4I3ge2QqhYe2-ExlaWmwBhIxDjIx5UrhM';


    /**
     * 授权回调
     */
    public function callback()
    {
//        error_reporting(E_ALL);
//        ini_set('display_errors', 1);
//        session_start();

        $wechatSDK = new \Org\Wechat\Wechat(C('WECHAT_OPTIONS'));
        if (isset($_GET['code'])) {
            $opts = $_GET;
            unset($opts['code'], $opts['state']);
            $urlStr = urldecode(http_build_query($opts));
            // 直接传递过来个base64编码的url 解码后直接回调
            $passingURL = trim(base64_decode($_GET['passingurl']), '/');

            try {
                $response = $wechatSDK->getOauthAccessToken();
                if (!$response or !isset($response['openid'])) {
                    throw new \Exception('getOauthAccessToken失败');
                }
            } catch (\Exception $e) {
                // 授权失败的话 就不授权了, 给个用户id 0 的 session
                $_SESSION['openid'] = '';
                $originURL = C('SITE_URL') . $passingURL;
                header("Location: {$originURL}");
                exit();
            }

            $_SESSION['openid'] = $response['openid'];

//            var_dump($_SESSION);
//            echo 1;
//            die();


            $url = C('SITE_URL');
            header("Location: {$url}");
            exit();
        } else {
            // TODO 用户拒绝了授权 log
            //
            $url = C('SITE_URL').'index.php?' . 'callback=fail';
            header("Location: {$url}");
            exit();
        }
    }

    /**
     * 创建菜单
     */
    public function menucreate()
    {
        // 写死地址, 避免出问题
//        $SITE_URL = C('SITE_URL');

        $array = array(
            'button' => array(
                array(
                    'name' => '在线预订',
                    'sub_button' => array(
                        array(
                            "type" => "view",
                            "name" => "查找客栈",
                            "url" => "http://m.miot.cn",
                        ),
                        array(
                            "type" => "view",
                            "name" => "精品客栈推荐",
                            "url" => "http://m.miot.cn/bestinn/",
                        ),
                        array(
                            "type" => "view",
                            "name" => "下载米途App",
                            "url" => "http://a.app.qq.com/o/simple.jsp?pkgname=com.miot.inn&g_f=991653",
                        ),
//                        array(
//                            "type" => "view",
//                            "name" => "周末好去处",
//                            "url" => "http://m.miot.cn/weekend/",
//                        ),,
                        array(
                            "type" => "view",
                            "name" => "查看微客栈订单",
                            "url" => "http://wx.miot.cn/weiinn/order/myorderlist?userfrom=wxmp",
                        ),
                    ),
                ),
                array(
                    'name' => '优惠活动',
//                    'type' => 'view',
//                    'url' => 'http://m.miot.cn/travelfund/share',
                    'sub_button' => array(
                        array(
                            "type" => "view",
                            "name" => "520元优惠券",
                            "url" => "http://m.miot.cn/travelfund/share",
                        ),
                        array(
                            "type" => "view",
                            "name" => "米途特卖汇",
                            "url" => "http://m.miot.cn/bigsale/",
                        ),
                        array(
                            "type" => "click",
                            "name" => "米途公社",
                            "key" => "gongshe"
                        ),
                    ),
                ),
                array(
                    "name" => "客栈推荐",
                    'sub_button' => array(
//                        array(
//                            "type" => "view",
//                            "name" => "避暑好去处",
//                            "url" => "http://m.miot.cn/theme/themeinn/themeid/213"
//                        ),
                        array(
                            "type" => "view",
                            "name" => "亲子客栈",
                            "url" => "http://m.miot.cn/theme/themeinn/themeid/211"
                        ),
//                        array(
//                            "type" => "view",
//                            "name" => "山乡生活",
//                            "url" => "http://m.miot.cn/theme/themeinn/themeid/201"
//                        ),
                        array(
                            "type" => "view",
                            "name" => "海景客栈",
                            "url" => "http://m.miot.cn/theme/themeinn/themeid/202",
                        ),
                        array(
                            "type" => "view",
                            "name" => "禅茶养心",
                            "url" => "http://m.miot.cn/theme/themeinn/themeid/212"
                        ),
                    ),
                ),
            ),
        );

        $wechatObj = new \Org\Wechat\Wechat(C('WECHAT_OPTIONS'));
        $wechatObj->resetAuth();
        $wechatObj->resetJsTicket();
        var_dump($wechatObj->createMenu($array));
        var_dump($wechatObj->errMsg);
        var_dump($wechatObj->errCode);
        var_dump($wechatObj->getMenu());
    }

    public function tmpsend()
    {
        $openId = 'o6FU9txpIiqQ-8R4dLsW5uyah_ug';
//        $openId = 'o6FU9t6bZarzE6UJNXzDgaxP0rxo';//刘钊
        $data1 = array(
            "address" => "北京市海淀区知春路甲481号",
            "room" => "标准间，1间",
            "date" => "2015年2月13日入住，2015年2月15日离店，住2晚",
            "name" => "刘超",
            "price" => "260"
        );
        $data2 = array(
            "address" => "北京市海淀区知春路甲482号",
            "goodsName" => "面包",
            "date" => "2015年2月13日 16:09",
            "price" => "5"
        );
        $data3 = array(
            "orderPrice" => "100",
            "orderInfo" => "米途微客栈 - 标准间，2015年2月13日入住，2015年2月15日离店，住2晚",
            "orderId" => "957868670719478"
        );
        $data4 = array(
            "orderInfo" => "米途微客栈 - 标准间，2015年3月12日入住，2015年3月15日离店，住3晚"
        );
        $wechat = new \Home\Logic\TemplatesentLogic();
        if($wechat->sendtemplates($openId, $data4, 'ROOM_ORDER_SUCCESS')) {
            echo 22;
            log_message('sendtemplates', '微信PUSH失败');
        }
    }

//    public function testtmpmsg()
//    {
//        // o6FU9tx9UOHgi6VJkk--fIpJuWoc
//        $payModel = new \Common\Model\PayModel();
//        $userModel = new \Common\Model\WxUserModel();
//        $payInfo = $payModel->getPayInfoByPayID('10097806');
//print_r($payInfo);
//        $userInfo = $userModel->findByID($payInfo['wxuserid']);
//print_r($userInfo);
//        $WxTemplatesModel = new \Weiinn\Model\WxTemplatesModel();
//        $data["innname"] = '乐江客栈';
//        $data["innaddress"] = "北京的天地可";
//        $data["trueprice"] = "100";
//        $data["innphone"] = "13641116360";
//        $data["guestname"] = '刘超';
//        $data["roominfo"] = "乐江客栈3间";
//        $data["date"] = "2015-06-15入住，2015-06-20离店，住5晚";
//        $templatetype = 'ROOM_ORDER_SUCCESS';
////        echo $res = $WxTemplatesModel->addTemplatesInfo($userInfo['openid'], $templatetype, $data);die;
//        $data = array(
//            'openid' => "o6FU9tx9UOHgi6VJkk--fIpJuWoc",
//            'templatetype' => $templatetype,
//            'data_info' => "great",
//            'createon' => date('Y-m-d H:i:s'),
//        );
//
//        $WxTemplatesModel->add($data);
//
////        $WxTemplatesModel->addTemplatesInfo("o6FU9tx9UOHgi6VJkk--fIpJuWoc", $templatetype, $data);
//        var_dump($WxTemplatesModel->getDbError());
//        var_dump($WxTemplatesModel->_sql());
//        var_dump($WxTemplatesModel->getError());
//    }
}
